<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="type === '编辑'?$t('编辑'):$t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'550px':'730px'" @close='close'>
    <div>
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'140px':'200px'" label-position="left" :rules="rules" style="margin:0 20px;">
        <el-form-item :label="$t('接口名称')" prop="ifname" key="ifname">
          <el-select v-model="record.ifname" ref="ospfIfname" filterable size='small' :placeholder="$t('请选择')" style="width:280px" :disabled="type === '编辑'">
            <el-option v-for="item in ifnameList" :disabled="ospfList.includes(item.strPhysicsName) || item.enPortMode !== 0 || !item.ipv4 || !item.ipv4[0].cPortIpv4" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('链路成本')" prop="cost" key="cost">
          <template slot="label">{{$t('链路成本')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:必须是整数，0-65535，0代表不设置，默认值为0')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.cost" ref="ospfCost" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('hello定时器')" prop="hello"  key="hello">
          <template slot="label">{{$t('hello定时器')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:接口向邻居发送hello报文的时间间隔，OSPF邻居之间的hello定时器的值要保持一致')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.hello" ref="ospfHello" style="width:280px" size='small'>
            <template slot="append">{{$t('秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('dead定时器')" prop="dead" key="dead">
          <template slot="label">{{$t('dead定时器')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:邻居失效时间，dead定时器应至少为hello时间间隔的4倍，OSPF邻居之间的dead定时器的值要保持一致。')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.dead" ref="ospfDead" style="width:280px" size='small'>
            <template slot="append">{{$t('秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('retransmit定时器')" prop="retransmit" key="retransmit">
          <template slot="label">{{$t('retransmit定时器')}}
            <el-tooltip class="item" effect="light" placement="top">
              <div slot="content">{{$t('提示信息')}}<br />
                {{$t('路由器向它的邻居通告一条LSA后，需要对方进行确认')}}<br />
                {{$t('若在重传间隔时间内没有收到对方的确认报文，就会向邻居重传这条LSA')}}<br />
                {{$t('OSPF邻居之间的retransmit定时器的值要保持一致。')}}</div>
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.retransmit" ref="ospfRetransmit" style="width:280px" size='small'>
            <template slot="append">{{$t('秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('OSPF认证方式')" prop="mode" key="mode">
          <el-radio-group v-model="record.mode" size='small'>
            <el-radio label="md5" class="ospfMd5">MD5</el-radio>
            <el-radio label="text" class="ospfText">{{$t('简单密码')}}</el-radio>
            <el-radio label="off" class="ospfOff">{{$t('关闭认证')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('MD5认证key_chain')" prop="key_chain" key="key_chain" v-if="record.mode === 'md5'">
          <template slot="label">{{$t('MD5认证key_chain')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:密钥的名字，字符串1-16个字符')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.key_chain" ref="ospfKeyChain" key="ospfKeyChain" style="width:280px" :placeholder="$t('请输入key_chain')" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('MD5认证key_id')" prop="key_id" key="key_id" v-if="record.mode === 'md5'">
          <template slot="label">{{$t('MD5认证key_id')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:整数，0-255')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.key_id" ref="ospfKeyId" key="ospfKeyId" style="width:280px" :placeholder="$t('请输入key_id')" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('密码认证String')" prop="string" key="string" v-if="record.mode === 'text'">
          <template slot="label">{{$t('密码认证String')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:字符串，1-8个字符')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.string" ref="ospfString" key="ospfString" style="width:280px" :placeholder="$t('请输入密码')" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('优先级')" prop="pri" key="pri">
          <template slot="label">{{$t('优先级')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息:整数，0-255，默认为1')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.pri" ref="ospfPri" style="width:280px" size='small'></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="ospfAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="ospfAddClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { getOspfIfconfig, setOspfIfconfig, addOspfIfconfig } from '@/api/network/route/dynamicRoute/OSPF'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'OspfDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateKeyChain = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (String(value).length > 16) {
        callback(new Error(this.$t('长度不能超过16个字符')))
      } else {
        callback()
      }
    }
    var validateKeyId = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 255 || Number(value) < 1) {
        callback(new Error(this.$t('请输入1-255之间的数字')))
      } else {
        callback()
      }
    }
    var validatePri = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 255 || Number(value) < 0) {
        callback(new Error(this.$t('请输入0-255之间的数字')))
      } else {
        callback()
      }
    }
    var validateString = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (String(value).length > 8) {
        callback(new Error(this.$t('长度不能超过8个字符')))
      } else {
        callback()
      }
    }
    var validateCost = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) > 65535) {
        callback(new Error(this.$t('必须在0-65535之间')))
      } else {
        callback()
      }
    }
    var validateSecond = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 1 || Number(value) > 65535) {
        callback(new Error(this.$t('必须在1-65535之间')))
      } else {
        callback()
      }
    }

    return {
      dialogVisible: false,
      lang: this.$i18n.locale,
      record: {
        mode: 'off',
        ifname: '',
        cost: '0',
        hello: '10',
        dead: '40',
        retransmit: '5',
        pri: '1',
        key_chain: '',
        key_id: '',
        string: ''
      },
      recordCopy: {
        mode: 'off',
        ifname: '',
        cost: '0',
        hello: '10',
        dead: '40',
        retransmit: '5',
        pri: '1',
        key_chain: '',
        key_id: '',
        string: ''
      },
      type: '',
      ifnameList: [],
      ospfList: [],
      rules: {
        ifname: [{ required: false, validator: validateName, trigger: 'change' }],
        cost: [{ required: false, validator: validateCost, trigger: 'blur' }],
        hello: [{ required: false, validator: validateSecond, trigger: 'blur' }],
        dead: [{ required: false, validator: validateSecond, trigger: 'blur' }],
        retransmit: [{ required: false, validator: validateSecond, trigger: 'blur' }],
        pri: [{ required: false, validator: validatePri, trigger: 'blur' }],
        key_chain: [{ required: false, validator: validateKeyChain, trigger: 'blur' }],
        key_id: [{ required: false, validator: validateKeyId, trigger: 'blur' }],
        string: [{ required: false, validator: validateString, trigger: 'blur' }]
      }
    }
  },
  computed: {
    change () {
      const { mode } = this.record
      return { mode }
    }
  },
  watch: {
    change: {
      handler (newValue) {
        if (newValue.mode === 'md5') {
          this.$nextTick(() => {
            const data = ['ospfKeyChain', 'ospfKeyId']
            inputClass(this.$refs, data)
          })
        } else if (newValue.mode === 'text') {
          this.$nextTick(() => {
            const data = ['ospfString']
            inputClass(this.$refs, data)
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    init (data, type) {
      this.dialogVisible = true
      getPhysicalApiArray().then(res => { // strPhysicsName
        if (res.status === 0) {
          this.ifnameList = res.info
        }
      })
      this.ospfList = []
      getOspfIfconfig().then(res => { // strPhysicsName
        if (res.status === 0) {
          for (let item of res.info) {
            this.ospfList.push(item.ifname)
          }
        }
      })
      this.type = type
      if (data) {
        this.record.mode = data.mode
        this.record.ifname = data.ifname
        this.record.cost = data.cost
        this.record.hello = data.hello
        this.record.dead = data.dead
        this.record.retransmit = data.retransmit
        this.record.pri = data.pri
        if (this.record.mode === 'md5') {
          this.record.key_chain = data.mode_info.key
          this.record.key_id = data.mode_info.keyid
        }
        if (this.record.mode === 'text') {
          this.record.string = data.mode_info.key
        }
      }
      this.$nextTick(() => {
        const data = ['ospfCost', 'ospfHello', 'ospfDead', 'ospfRetransmit', 'ospfPri']
        const selectData = ['ospfIfname']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type === '编辑') {
            setOspfIfconfig(this.record).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.ospfConfigListInfo()
              }
            })
          } else {
            addOspfIfconfig(this.record).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.ospfConfigListInfo()
              }
            })
          }
        }
      })
    },
    close () {
      this.type = ''
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
      this.ifnameList = []
      this.ospfList = []
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
